﻿/*****************************************************************************
 * Utility.cs: Utility 0.1
 *****************************************************************************
 * Copyright (C) 2005 Jon Lech Johansen <jon@nanocrew.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

using System;
using System.IO;
using System.Security.Cryptography;

namespace JustePort
{
    public class Utility
    {
        public static void LeReverse(byte[] arr, int index, int length)
        {
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(arr, index, length);
            }
        }

        public static void LeReverse(byte[] arr)
        {
            LeReverse(arr, 0, arr.Length);
        }

        public static int IndexOf(byte[] buf, uint val)
        {
            for (int i = 0; i < (buf.Length - 3); i += 4)
            {
                if (BitConverter.ToUInt32(buf, i) == val)
                    return i;
            }

            return -1;
        }

        public static void RijndaelDecrypt(byte[] Buf, int Offset, int Count,
                                            byte[] Key, byte[] IV)
        {
            Rijndael alg = Rijndael.Create();
            alg.Mode = CipherMode.CBC;
            alg.Padding = PaddingMode.None;

            MemoryStream ms = new MemoryStream();

            ICryptoTransform ct = alg.CreateDecryptor(Key, IV);
            CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(Buf, Offset, (Count / 16) * 16);
            cs.Close();

            ms.ToArray().CopyTo(Buf, Offset);
        }
    }
}